package com.lou1052.redis.jedis.ext.client.shard;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.util.Hashing;

import java.util.List;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/10/25
 * Time: 22:42
 * To change this template use File | Settings | File Templates.
 */
public class ShardedJedisExtFactory implements PooledObjectFactory<ShardedJedisExt> {
    private List<JedisShardInfo> shards;
    private Hashing algo;
    private Pattern keyTagPattern;

    public ShardedJedisExtFactory(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
        this.shards = shards;
        this.algo = algo;
        this.keyTagPattern = keyTagPattern;
    }

    @Override
    public PooledObject<ShardedJedisExt> makeObject() throws Exception {
        ShardedJedisExt jedis = new ShardedJedisExt(shards, algo, keyTagPattern);
        return new DefaultPooledObject<ShardedJedisExt>(jedis);
    }

    @Override
    public void destroyObject(PooledObject<ShardedJedisExt> pooledShardedJedis) throws Exception {
        final ShardedJedisExt ShardedJedisEx = pooledShardedJedis.getObject();
        for (Jedis jedis : ShardedJedisEx.getAllShards()) {
            try {
                try {
                    jedis.quit();
                } catch (Exception e) {

                }
                jedis.disconnect();
            } catch (Exception e) {

            }
        }
    }

    @Override
    public boolean validateObject(PooledObject<ShardedJedisExt> pooledShardedJedis) {
        try {
            ShardedJedisExt jedis = pooledShardedJedis.getObject();
            for (Jedis shard : jedis.getAllShards()) {
                if (!shard.ping().equals("PONG")) {
                    return false;
                }
            }
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    @Override
    public void activateObject(PooledObject<ShardedJedisExt> p) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<ShardedJedisExt> p) throws Exception {

    }
}
